<?php
/**
 *发红包
 */
namespace App;
defined('IN_IA') or exit('Access Denied');

use Model\OrderMod;
use Model\RedBatchMod;
use Model\RedMod;
use Model\RedQuestionMod;
use Model\RedRecordMod;
use Pri\red\RedLuckPrivate;
use Pub\tool\Tool;
use Pub\wx\WxPay;

class Red extends Action
{
    private $Red = null;  //红包mod
    private $RedRecord = null;  //红包记录
    private $WxPay = null;  //微信红包tool
    private $Order = null;  //支付订单mod
    private $RedBatch = null;  //红包分批mod
    private $RedLuck = null;  //手气红包action
    private $RedQuestion = null;  //红包答题

    public function __construct()
    {
        parent::__construct();
        $this->Red = new RedMod();
        $this->getUid();
    }

    /**
     * 发红包
     * @param data 数据
     * @return red_id 返回发布的红包id
     */
   public function publish()
   {
       $_question = array();
       $this->_gpc["data"]["uid"] = $this->_uid;
       if(isset($this->_gpc["data"]["question"])){
           $_question = $this->_gpc["data"]["question"];
           $_open_check = $this->_gpc["data"]["open_check"];
           unset($this->_gpc["data"]["question"]);
       }
       if($this->_gpc["data"]["area_type"] > 0){
           $this->_gpc["data"]["area"] = json_encode($this->_gpc["data"]["area"]);
       }
       $this->_gpc['data']['time'] = TIMESTAMP;
       $this->_gpc["data"]["uniacid"] = $this->_uniacid;
        if($this->Red->insert($this->_gpc['data'])){
            $_red_id = pdo_insertid();
            //红包验证问题
            if(count($_question) > 0){
                $_question["red_id"] = $_red_id;
                if($_open_check == 1){
                    $_question["options"] = json_encode($_question["options"]);
                }
                $this->addQuestion($_question);
            }
            $this->_result = array('status'=>'success','data'=>$_red_id);
        }
        $this->result($this->_result);
   }

    /**
     * 新增红包答题信息
     * @param array $_data 数据
     * @return boolean 是否新增成功
     */
   private function addQuestion($_data)
   {
        $this->RedQuestion = new RedQuestionMod();
        return $this->RedQuestion->insert($_data);
   }

    /**
     * 获取发包微信支付参数
     * @param red_id 红包id
     */
   public function publishPayParams()
   {
       $_red = $this->Red->findOne(array('id'=>$this->_gpc['red_id']),array('pay','uid'));
        $_order_id = $this->createPayOrder($_red['uid'],$_red['pay'],$this->_gpc['red_id']);
        if(!$_order_id){
            $this->_result = array('status'=>'error','err_status'=>1,'err_msg'=>'创建红包失败');
            $this->result($this->_result);
        }
        $this->WxPay = new WxPay($_order_id);
        $_fans = $this->uidToFans($_red['uid']);
        $_openid = KUYUAN_DEBUG ? 'oxYQT1DAyMPEFXMzjjJ-Rz1OQa-c' : $_fans['openid'];
        $_create_order = $this->WxPay->createOrder($_openid,$_red['pay'],\Pub\tool\Setting::get(\Pub\tool\Setting::WEB_NAME)."发红包");
        if($_create_order['status'] == 'error') $this->result($_create_order);
        $_data = $this->WxPay->jsPayParam();
        $_data['order_id'] = $_order_id;
        $this->_result = array('status'=>'success','data'=>$_data);
        $this->result($this->_result);
   }

    /**
     * 创建本地微信支付订单
     * @param string $_uid 用户id
     * @param string $_money 订单金额
     * @param string $_red_id 红包id
     * @return string
     */
   private function createPayOrder($_uid,$_money,$_red_id)
   {
        $this->Order = new OrderMod();
        $_order_id = Tool::createOrder();
        $_data = array(
            'uniacid'=>$this->_uniacid,
            'uid'=>$_uid,
            'order_id'=>$_order_id,
            'money'=>$_money,
            'source_id'=>$_red_id,
            'source'=>'red'
        );
        return $this->Order->insert($_data) ? $_order_id : false;
   }

    /**
     * 发红包支付成功，更改红包状态，更改订单状态
     * @param integer red_id 红包id
     * @param integer order_id 订单id
     * @param integer type 红包类型 1=手气红包 2=普通红包
     */
   public function publishPaySuccess()
   {
        //手气红包，生成红包数据
        if($this->_gpc["type"] == 1){
            $_red = $this->Red->findOne(array("id"=>$this->_gpc["red_id"]),array("money","number"));
            //手气红包对象
            $this->RedLuck = new RedLuckPrivate();
            if($_red["number"] >= KUYUAN_LUCK_RED_DIVISOR*2){
                //红包分批,更快生成红包，返回给发包用户，在用户开红包的时候分批生成剩余的红包
                $_batch = $this->RedLuck->batch($_red["money"],$_red["number"]);
                $_batch["red_id"] = $this->_gpc["red_id"];
                $this->RedBatch = new RedBatchMod();
                $this->RedBatch->insert($_batch);
                //单批红包的数据
                $_red["number"] = KUYUAN_LUCK_RED_DIVISOR;
                $_red["money"] = $_batch["money"];
            }
            $_red_record = $this->RedLuck->redPicket($_red["money"],$_red["number"]);
            //生成红包记录
            $this->RedRecord = new RedRecordMod();
            $_record = array(
                "uniacid"=>$this->_uniacid,
                "uid"=>0,
                "red_id"=>$this->_gpc["red_id"]
            );
            foreach($_red_record as $_v){
                $_record["money"] = $_v;
                $this->RedRecord->insert($_record);
            }
        }
        //修改红包状态
        $this->Red->update(array('status'=>2),array('id'=>$this->_gpc['red_id']));
        $this->Order = new OrderMod();
        $this->Order->update(array('status'=>2),array('order_id'=>$this->_gpc['order_id']));
        $this->_result = array('status'=>'success');
        $this->result($this->_result);
   }


    /**
     * 发红包支付失败，删除红包
     * @param red_id 红包id
     */
   public function publishPayError()
   {
       if($this->Red->delete(array('id'=>$this->_gpc['red_id']))){
           $this->_result = array('status'=>'success');
       }
       $this->result($this->_result);
   }
}